package com.springboot.onlinemusicserver.interceptor;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;

import static com.springboot.onlinemusicserver.utils.common.SessionAttribute.USERINFO;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-05-21
 * Time: 11:05
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 对于未登录的用户进行拦截处理
        HttpSession session = request.getSession(false);
        if (session == null ||session.getAttribute(USERINFO) == null) {
            // 用户未登录
            // 设置响应码以及响应数据
            response.setStatus(401);
            response.setContentType("text/plain;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            try (ServletOutputStream out = response.getOutputStream()) {
                out.write("用户未登录".getBytes(StandardCharsets.UTF_8));
            }
            return false;
        }
        return true;
    }
}
